package it11.Capood.GUI;

import it11.Capood.R;
import it11.Capood.DataLogic.BluetoothService;
import it11.Capood.DataLogic.ClipListenService;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.CheckBox;

public class SettingsActivity extends Activity {

	//GUI
	private CheckBox bluetooth_toggle;
	private CheckBox clip_toggle;
	private SharedPreferences prefs;
	
	//fields
	private boolean bluetooth_running = false;
	private boolean clip_running = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		
		bluetooth_toggle = (CheckBox) findViewById(R.id.checkBox_bluetooth_service);
		clip_toggle = (CheckBox) findViewById(R.id.checkBox_clip_service);
		
		
		prefs = getSharedPreferences(MainActivity.PREF_CAPOOD, Context.MODE_PRIVATE);
	}
	
	@Override
	public void onStart(){
		super.onStart();
		
		clip_running = prefs.getBoolean(ClipListenService.PREF_CLIP_SERVICE, ClipListenService.isRunning());
		clip_toggle.setChecked(ClipListenService.isRunning());
		
		bluetooth_running = prefs.getBoolean(BluetoothService.PREF_BLUETOOTH_SERVICE, BluetoothService.isRunning());
		bluetooth_toggle.setChecked(bluetooth_running);
	}


	public void click_toggles(View view){
		Intent service_intent = new Intent(this,ClipListenService.class);
		
		clip_running = prefs.getBoolean(ClipListenService.PREF_CLIP_SERVICE, ClipListenService.isRunning());
		
		if (clip_toggle.isChecked() != clip_running) {
			SharedPreferences.Editor editor = prefs.edit();
			if (clip_toggle.isChecked()) {
				startService(service_intent);
				editor.putBoolean(ClipListenService.PREF_CLIP_SERVICE, true);
			} else {
				stopService(service_intent);
				editor.putBoolean(ClipListenService.PREF_CLIP_SERVICE, false);
			}
			
			editor.apply();
		}
		
		service_intent = new Intent(this,BluetoothService.class);
		
		bluetooth_running = prefs.getBoolean(BluetoothService.PREF_BLUETOOTH_SERVICE, BluetoothService.isRunning());
		
		if (bluetooth_toggle.isChecked() != bluetooth_running) {
			SharedPreferences.Editor editor = prefs.edit();
			if (bluetooth_toggle.isChecked()) {
				startService(service_intent);
				editor.putBoolean(BluetoothService.PREF_BLUETOOTH_SERVICE, true);
			} else {
				stopService(service_intent);
				editor.putBoolean(BluetoothService.PREF_BLUETOOTH_SERVICE, false);
			}
			
			editor.apply();
		}
	}

}
